from fastapi import APIRouter, HTTPException
from typing import List
from backend.api.email_service import EmailService
from backend.models import (
    ServiceStatusResponse,
    StatsResponse,
    ProcessedEmail,
    StartServiceResponse,
    StopServiceResponse
)

router = APIRouter(prefix="/email", tags=["email"])

# 全局邮件服务实例
email_service = EmailService()

@router.get("/status", response_model=ServiceStatusResponse)
async def get_service_status():
    """获取服务状态 - HTTP接口层"""
    try:
        status = email_service.get_service_status()
        return ServiceStatusResponse(**status)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/start", response_model=StartServiceResponse)
async def start_service():
    """启动服务 - HTTP接口层"""
    try:
        result = email_service.start_service()
        return StartServiceResponse(**result)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/stop", response_model=StopServiceResponse)
async def stop_service():
    """停止服务 - HTTP接口层"""
    try:
        result = email_service.stop_service()
        return StopServiceResponse(**result)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/stats", response_model=StatsResponse)
async def get_statistics():
    """获取统计信息 - HTTP接口层"""
    try:
        stats = email_service.get_statistics()
        return StatsResponse(**stats)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/processed", response_model=List[ProcessedEmail])
async def get_processed_emails(limit: int = 50):
    """获取已处理的邮件 - HTTP接口层"""
    try:
        emails = email_service.get_processed_emails(limit)
        return [ProcessedEmail(**email) for email in emails]
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))